<template>
  <div>
    <el-table :data="filesTypeArr" style="width: 100%">
      <el-table-column show-overflow-tooltip label="文件名">
        <template slot-scope="scope">
          <span v-menus="{obj:scope.row}">{{ scope.row.sourceFileName }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="extName" label="类型" />
      <el-table-column show-overflow-tooltip prop="creationTime" label="上传时间" />
    </el-table>
    <div class="clearfix" style="marginTop:15px;">
      <el-button type="primary" class="right" style="marginRight:5px;" @click="openUpload">
        上传
        <i class="el-icon-upload el-icon--right" />
      </el-button>
    </div>
    <!-- <Pagination /> -->
    <el-dialog
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      title="上传文件"
      :visible.sync="dialogVisible"
      width="450px"
      :before-close="handleClose"
    >
      <div class="upload-demo">
        <div tabindex="0" class="el-upload el-upload--text">
          <el-button type="primary" @click="showSelectVideo">选择文件</el-button>
          <el-button type="success" :disabled="cancle" @click="authUpload">上传到服务器</el-button>
          <input
            id="fileId"
            ref="emptyInput"
            type="file"
            name="file"
            class="el-upload__input"
            @change="changeSelectFile"
          >
        </div>
        <ul class="el-upload-list el-upload-list--text">
          <li v-if="file.fileName" tabindex="0" class="el-upload-list__item is-success">
            <a class="el-upload-list__item-name">
              <i class="el-icon-document" />
              {{ file.fileName }}
            </a>
            <div
              role="progressbar"
              aria-valuenow="1"
              aria-valuemin="0"
              aria-valuemax="100"
              class="el-progress el-progress--line"
            >
              <div class="el-progress-bar">
                <div class="el-progress-bar__outer" style="height: 2px;">
                  <div class="el-progress-bar__inner" :style="{width:authProgress + '%'}" />
                </div>
              </div>
              <div class="el-progress__text" style="font-size: 12.8px;">{{ authProgress }}%</div>
            </div>
          </li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitFile">确 定</el-button>
      </span>
    </el-dialog>
    <ul v-show="menuShow" class="contextmenu" :style="{'top':menuTop,'left': menuLeft}">
      <li @click="deleteShop">下载</li>
      <li @click="menuShow = false;">关闭</li>
    </ul>
  </div>
</template>

<script>
const client = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAIxZYjNPM6pgO3',
  accessKeySecret: '11iG8LcwySD1Ryw8aT1PVrQitMNYUl',
  bucket: 'syg-photo'
})
import Pagination from '../commom/pagination';
import axios from 'axios';
import mmUrl from '~/utils/utilUrl';
import OSS from 'ali-oss';
export default {
  components: {
    Pagination
  },
  directives: {
    menus: {
      inserted: function(el, binding, vnode) {
        const result = binding.value.obj
        let vm = vnode.context
        vnode = vnode.elm
        el.oncontextmenu = event => {
          event.preventDefault()
        };
        el.onmouseup = event => {
          if (event.button === 2) {
            vm.menuShow = true
            vm.menuLeft = event.pageX + 'px';
            vm.menuTop = event.pageY + 'px';
            vm.selectFilesObj = result
          }
        }
      }
    }
  },
  props: ['filesType', 'id'],
  data() {
    return {
      authProgress: 0,
      fileInfoMation: {},
      cancle: true,
      dataId: this.$props.id,
      selectFilesObj: {},
      dialogVisible: false,
      file: {
        fileName: ''
      },
      filesTypeArr: [],
      menuShow: false,
      menuLeft: 0, // 插件参数
      menuTop: 0 // 插件参数
    }
  },
  watch: {
    filesType: {
      immediate: true, // 这句重要
      handler(val) {
        this.filesTypeArr = val
      }
    }
  },
  methods: {
    deleteShop() {
      // 下载
      this.menuShow = false
      let downloadObj = this.selectFilesObj
      const result = client.signatureUrl(`${downloadObj.fileName}`, {
        response: {
          'content-disposition': `attachment; filename=${downloadObj.sourceFileName}`
        }
      })
      this.download(result, downloadObj)
    },
    download(data, downloadObj) {
      if (!data) {
        return
      }
      const link = document.createElement('a')
      link.style.display = 'none';
      link.href = data
      link.setAttribute('download', `${downloadObj.sourceFileName}`)
      document.body.appendChild(link)
      link.click()
    },
    submitFile() {
      if (this.authProgress !== 100) {
        return false
      }
      this.$post({
        url: mmUrl.file.uploadFile,
        data: {
          items: [this.file]
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.$refs['emptyInput'].value = '';
        this.authProgress = 0
        this.file.fileName = null
        this.cancle = true
        this.file.fileName = '';
        this.dialogVisible = false
        this.$post({
          url: mmUrl.file.getfiles,
          data: {
            dataId: this.$props.id,
            typeCode: 'COMPANY_FILE_FILE'
          }
        }).then(res => {
          this.filesTypeArr = res
        })
      })
    },
    showSelectVideo() {
      this.$refs['emptyInput'].value = '';
      document.getElementById('fileId').click()
    },
    authUpload() {
      this.cancle = true
      let that = this
      let arr = this.fileInfoMation.name.split('.')
      let extName = arr[arr.length - 1]
      let sourceFileName =
        'file-' + this.fileInfoMation.name + '-' + Date.parse(new Date())
      client.put(sourceFileName, this.fileInfoMation).then(res => {
        const newImageInfo = {
          dataId: that.$props.id,
          dataType: '公司文档',
          extName: '.' + extName,
          fileName: sourceFileName,
          fileType: 1,
          fileUrl: res.url,
          ident: 1,
          size: (this.fileInfoMation.size / 1024).toFixed(2),
          sort: 0,
          sourceFileName: this.fileInfoMation.name,
          typeCode: 'COMPANY_FILE_FILE'
        }
        that.file = JSON.parse(JSON.stringify(newImageInfo))
        that.authProgress = 100
      })
    },
    changeSelectFile(res) {
      this.authProgress = 0
      this.fileInfoMation = res.target.files[0]
      this.$set(this.file, 'fileName', this.fileInfoMation.name)
      this.cancle = false
    },
    openUpload() {
      this.dialogVisible = true
    },
    handleClose() {
      this.$refs['emptyInput'].value = '';
      this.fileInfoMation = {}
      this.file.fileName = null
      this.dialogVisible = false
      this.authProgress = 0
      this.cancle = true
    }
  }
}
</script>
<style>
.contextmenu {
  margin: 0;
  background: #fff;
  width: 100px;
  z-index: 100;
  position: fixed;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.3);
}
.contextmenu li {
  text-indent: 20px;
  margin: 0;
  width: 100%;
  line-height: 36px;
  cursor: pointer;
  border: 0px;
}

.contextmenu li:hover {
  background: #eee;
}
</style>
